package com.opennews.openplatform.service;

import com.opennews.openplatform.entity.tables.records.RegionRecord;
import com.opennews.openplatform.jooq.DSLContextWrapper;
import com.opennews.openplatform.jooq.RecordHelper;
import com.opennews.openplatform.myspringbootcore.util.SharedUtil;
import lombok.RequiredArgsConstructor;
import org.jooq.DSLContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.opennews.openplatform.entity.Tables.REGION;

@RequiredArgsConstructor
@Service
public class RegionService {
    private final DSLContext dslContext;
    private final DSLContextWrapper dslContextWrapper;
    private final Environment env;

    /**
     * Prepares the initial data for region.
     */
    public void init() {
        if (dslContextWrapper.count(REGION) == 0) {
            List<RegionRecord> records = new ArrayList<>();
            records.add(createRecord("柬埔寨", "cambodia"));
            records.add(createRecord("马来西亚", "malaysia"));
            records.add(createRecord("新加坡", "singapore"));
            records.add(createRecord("泰国", "thailand"));
            dslContext.batchInsert(records);
        }
    }

    /**
     * Gets region flag url based on its name.
     *
     * @param name: The region name.
     * @return The full url of the region flag.
     */
    public String getFlagUrl(String name) {
        return !SharedUtil.isNullOrEmpty(name) ?
                String.format("%s%s/%s.png", env.getProperty("resource.httpBaseUrl"), env.getProperty("resource.regionFlagUrl"), name.toLowerCase()) :
                "";
    }

    /**
     * Queries all regions.
     *
     * @return List of map instance which contains keys below.
     * id: String of region id.
     * name: String of region name.
     * title: String of region title.
     * flagUrl: String of region flag url.
     */
    public List<Map<String, Object>> queryAll() {
        return dslContext.select(
                        REGION.ID.as("id"),
                        REGION.NAME.as("name"),
                        REGION.TITLE.as("title")
                )
                .from(REGION)
                .orderBy(REGION.NAME.asc())
                .fetch()
                .map(p -> {
                    Map<String, Object> item = p.intoMap();

                    // Adds logoUrl key to this map item.
                    item.put("flagUrl", getFlagUrl(item.get("name").toString()));

                    return item;
                });
    }

    private RegionRecord createRecord(String title, String name) {
        RegionRecord record = dslContext.newRecord(REGION);
        RecordHelper.setCommonFields(record);
        record.setTitle(title);
        record.setName(name);

        return record;
    }
}
